package com.shijie.socket;

import com.shijie.exception.OtherException;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint(value = "/ws/submit/{submitId}", configurator = CorsServerEndpointConfig.class)
public class CompleteSocket {
    private static final ConcurrentHashMap<Long, Session> map = new ConcurrentHashMap<>();

    @OnOpen
    public void onopen(Session session, EndpointConfig config, @PathParam("submitId") Long submitId) {
//        if (map.containsKey(submitId)) {
//            try (Session se = map.remove(submitId)) {
//                log.info("delete session: {}", se);
//            } catch (IOException e) {
//                log.error(e.toString());
//            }
//        }
        map.put(submitId, session);
        log.info("--onOpen session, submitId: {}, {}", session, submitId);
    }

    @OnMessage
    public void onmessage(Session session, String message) {
        log.info("--onMessage session: {}", session);
        log.info("--onMessage: {}", message);
    }

    @OnClose
    public void onclose(Session session, CloseReason closeReason, @PathParam("submitId") Long submitId) {

        try (Session remove = map.remove(submitId)) {
            log.info("--onClose Reason: {}", closeReason.toString());
            log.info("--onClose session: {}", session);
        } catch (IOException e) {
            throw new OtherException(e.toString());
        }

    }

    @OnError
    public void onerror(Session session, Throwable throwable) {
        log.error("--onError session: {}", session);
        log.error("--onError: {}", throwable.toString());
    }

    public static void sendMessage(Long submitId, String jsonMsg) {
        map.forEach((key, val) -> System.out.println(key + "--:--" + val));
        Session session = map.get(submitId);
        log.info("--sendMessage submitId【{}】--:--session【{}】", submitId, session);

        try {
            session.getBasicRemote().sendText(jsonMsg);
        } catch (IOException e) {
            throw new OtherException(e.toString());
        }
    }

    public static void close(Long submitId) {
        try (Session session = map.remove(submitId)) {
            log.info("socket:【{}】--close", session.getId());
        } catch (IOException e) {
            log.error(e.toString());
        }
    }

}
